/**
 * Created by ZFL on 2018/1/31.
 */
var vm=new Vue({
    el:'#home',
    data:{
        couponsList:[]
    }
})
var mallStoreId=0;
function PageInit(){
    //定位
    if(!window.sessionStorage["isLocation"]){
        getLocaltion();   //获得地理位置
        window.sessionStorage["isLocation"] ='1';
    }else{
        document.getElementById("address").innerHTML = $.getStorage('yd_address');
    }


    if (com_obj.mallStoreId) {
        mallStoreId = com_obj.mallStoreId;
    } else if ($.getPara("mallStoreId")!= "") {
        mallStoreId = $.getPara("mallStoreId");
    }
    getBrand();   //店铺信息
    getCoupons();   //优惠券
    getStoreHotSales();//热销单品
}
//点击背景图   店铺logo   查看店铺详情信息
function storeDetails(){
    window.location.href='./b2c/member/storeInfo.html?mallStoreId='+mallStoreId
}
//店铺信息
function getBrand() {
    $.ajaxHandler({
            model: function(){
                var obj = {};
                obj.storeId=mallStoreId;

                return obj;
            },
            visibleTime: 100,
            dataType: "json",
            //api: 'yg_baijiaplatform/baUser/getStoreInformation',
            api:'yg_baijiaplatform/baUser/getStoreInformation',
            success: function (result) {
                //console.log(result);
                if (result.code == 10000) {
                    var data = result.data;
                    $('.logo h1').text(data.storeName);
                    document.title = data.storeName;
                    //店铺背景图
                    if (data.backImage.toString().indexOf("http") < 0) {
                        $(".home-banner").css("background-image", "url("+$.imgApi()+ "" + data.logoPath+")");
                    } else {
                        $(".home-banner").css({
                            'background-image':'url('+data.backImage+')',
                            'height':$('.home-banner').width()*0.33
                        });
                    }
                    //店铺logo图
                    $('.storeLogo img').attr('src',data.logoPath);

                    //店铺名称
                    $('.storeName span').html(data.storeName)


                    //电话联系
                    $('.storeTel a').attr('href','tel:'+data.tel)

                    if(data.priceNoFreight<=0||data.priceNoFreight=="999999"||data.priceNoFreight==999999){
                        $(".hint-2").hide();
                    }else {
                        $(".hint-2").show();
                    }
                    $('.hint-2 i').text(divideNumber(data.priceNoFreight, 100));
                    if($(".hint-1").css("display")=="none" && $(".hint-2").css("display")=="none"){
                        $(".juan-warp").hide();
                    }
                } else {
                    $.toast('异常', 'text');
                    //console.log(result);
                }

            }
        }
    );
}

//优惠劵
function getCoupons() {
    $.ajaxHandler({
            model: function () {
                var obj = {};
                if (com_obj.mallStoreId) {
                    obj.mallStoreId = com_obj.mallStoreId;
                } else {
                    obj.mallStoreId = $.getPara("mallStoreId");
                }

               obj.position=1
                return obj;
            },
            visibleTime: 100,
            dataType: "json",
            api:'yg_baijiaplatform/baPromotion/storePromotions',
            success: function (result) {
                if(result.code=10000){
                    var data=result.data;

                    if(data.length>0){
                        $('.couponWrap').css({
                            'width':data.length*3.2+'rem'

                        })

                        data.forEach(function(value,index){
                            var image='./b2c/images/tyquan.png'
                            value.limited=divideNumber(value.limited,100);
                            value.amount=divideNumber( value.amount,100)

                            //console.log( vm.couponsList)

                            if(value.type==2){
                                //通用券
                                value.backgroundPath='./b2c/images/home/tyquan.png';
                                value.text="全部商品可用"


                            }else if(value.type==3){
                                //品牌券

                                value.backgroundPath='./b2c/images/home/ppquan.png';
                                if(data.brandName &&　data.brandName!=""){
                                    value.text="仅限"+data.brandName+'使用';
                                }
                            }else if(value.type=5){
                                //商品券
                                value.backgroundPath='./b2c/images/home/spquan.png';
                                if(data.goodsName &&　data.goodsName!=""){
                                    value.text="仅限"+data.goodsName+'使用';
                                }
                            }

                            vm.couponsList.push(value);




                        })
                    }
                }
            }
        }
    );
}

//领取优惠劵
function coupons(id) {
    var obj = {};
    obj.promotionDetailId=id;
    obj.userId = com_obj.userId;
    $.ajaxHandler({
            model: function () {
                //console.log(obj)
                return obj;
            },
            visibleTime: 100,
            dataType: "json",
            api:'yg_baijiaplatform/baPromotion/coupons',
            success: function (result) {
                var data = result.data;
                if (result.code == 10000) {
                    YDUI.dialog.toast('领取成功','success',1000)
                } else if (result.code == 30109) {
                    YDUI.dialog.toast(result.message,1000)
                } else {
                    YDUI.dialog.toast('您已领取过该优惠券',1000)
                }
            }
        }
    );
}
//热销单品
var pageNum = 1;
var pageSize =20;
function getStoreHotSales() {
    var obj = {};
    obj.pageNum = pageNum;
    obj.pageSize = pageSize;
    if (com_obj.mallStoreId) {
        obj.storeId = com_obj.mallStoreId;
    } else {
        obj.storeId = $.getPara("mallStoreId");
    }

    if (com_obj.userId) {
        obj.userId = com_obj.userId;
    } else {
        obj.userId = 0;
    }
    $.ajaxHandler({
            model: function () {
                return obj;
            },
            visibleTime: 100,
            dataType: "json",
            api: 'yg_baijiaplatform/goods/getStoreHotSales',

            success: function (result) {
                //console.log(result);
                if (result.code == 10000) {
                    var data = result.data.list;
                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            if (data[i]["goodsImage"].toString().indexOf('http') < 0) {
                                data[i]["goodsImage"] = $.imgApi() + "" + data[i]["goodsImage"];
                            }
                            data[i]["lowestPrice"] = divideNumber(data[i]["lowestPrice"], 100).toFixed(2);
                            data[i]["suggestedPrice"] = divideNumber(data[i]["suggestedPrice"], 100).toFixed(2);
                            data[i].href='./b2c/goods/goods.html?goodsId='+data[i].goodsId+'&mallStoreId='+$.getPara("mallStoreId")+'&userTalentId='+$.getPara("userTalentId")+'';
                        }
                        var source = $("#hotGoods-template").html();
                        var template = Handlebars.compile(source);
                        var dataObj = {};
                        dataObj.data = data;
                        $('.hot-list-box').append(template(dataObj));

                        //如果实际售价大于等于建议价则建议价隐藏
                        for (var j = 0; j < data.length; j++) {
                            if (divideNumber(data[j]["lowestPrice"], 100) - divideNumber(data[j]["suggestedPrice"], 100) >= 0) {
                                $(".r-price-" + data[j].goodsId + "").hide();
                            }
                        }
                    } else {
                        if (pageNum > 1) {
                            //$.toast("没有数据了","text");
                            $("body").destroyInfinite();
                        }
                    }
                } else {
                    $.toast('异常', 'text');
                    //console.log(result);
                }
            }
        }
    );
}







//点击地址icon进行重新定位
$('.home-icon').click(function(e){
    getLocaltion();
    e.stopPropagation();
})

function getLocaltion(){
    // 百度地图API功能
    var map = new BMap.Map("allmap");
    var point = new BMap.Point(108.95,34.27);
    map.centerAndZoom(point,12);

    var geolocation = new BMap.Geolocation();
    geolocation.getCurrentPosition(function(r){console.log(r.point)
        if(this.getStatus() == BMAP_STATUS_SUCCESS){
            var mk = new BMap.Marker(r.point);
            map.addOverlay(mk);//标出所在地
            map.panTo(r.point);//地图中心移动
            window.localStorage.setItem('userlatitude',r.point.lat);
            window.localStorage.setItem('userlongitude',r.point.lng);
            var point = new BMap.Point(r.point.lng,r.point.lat);//用所定位的经纬度查找所在地省市街道等信息
            var gc = new BMap.Geocoder();
            gc.getLocation(point, function(rs){
                var addComp = rs.addressComponents;
                //console.log(JSON.stringify(rs));//地址信息
                document.getElementById("address").innerHTML = rs.address;
                window.localStorage.setItem('yd_address',rs.address);
                YDUI.dialog.toast('定位成功',1000)

            });
        }else {
            alert('failed'+this.getStatus());
        }
    },{enableHighAccuracy: true})
}
